package com.letfox.finance.interceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.letfox.common.enums.ResponseEnum;
import com.letfox.common.model.ResultResponse;
import com.letfox.common.util.JacksonUtil;
import com.letfox.common.util.http.HTTPResponseUtil;
import com.letfox.user.contants.AccountCacheContants;
import com.letfox.user.service.AccountCacheService;
import com.letfox.user.service.relation.AccountServiceKeyService;

/**
 * Spring全局拦截器
 */
public class Interceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory.getLogger(Interceptor.class);
	
	@Autowired
	private AccountServiceKeyService accountServiceKeyService;
	@Autowired
	private AccountCacheService accountCacheService;

	

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		String url = request.getRequestURI().replace(request.getContextPath(), "");
		//检查认证
		if(!checkAuth(request)){
			ResultResponse resultResponse = ResultResponse.getFailInstance(ResponseEnum.R201.getMessage());
			HTTPResponseUtil.renderText(response, JacksonUtil.toJson(resultResponse));
			return false;
		}
		//检查权限
		if(!checkAuthorition(request)){
			ResultResponse resultResponse = ResultResponse.getFailInstance(ResponseEnum.R403.getMessage());
			HTTPResponseUtil.renderText(response, JacksonUtil.toJson(resultResponse));
			return false;
		}
		return true;
	}
	
	/**
	 * 检查权限
	 * @param request
	 * @return
	 */
	private boolean checkAuthorition(HttpServletRequest request){
		String url = request.getRequestURI().replace(request.getContextPath(), "");
		String account = request.getParameter("account");
		//获取用户缓存中权限
		String accountAuthKey= AccountCacheContants.ACCOUNT_AUTH + account;
		Map<String, Object> accountAuth = accountCacheService.getAccountAuth(accountAuthKey);
		
		
		//检查用户权限
		for (String key : accountAuth.keySet()) {
			String accountAuthURL = (String) accountAuth.get(key);
			if(url.equals(accountAuthURL)){
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * 检查认证
	 * @param request
	 * @return
	 */
	private boolean checkAuth(HttpServletRequest request) {
		String account = request.getParameter("account");
		String serviceKey = request.getParameter("serviceKey");
		//检验账号
		if(StringUtils.isBlank(account)){
			return false;
		}
		//检验服务KEY
		if(StringUtils.isBlank(serviceKey)){
			return false;
		}
		
		String cacheAccountServiceKey = AccountCacheContants.ACCOUNT_SERVICE_KEY + account;
		//从缓存查找账号和服务KEY
		String accountServiceKey = (String) accountCacheService.getAccountServiceKey(cacheAccountServiceKey);
		if(StringUtils.isBlank(accountServiceKey)){
			return false;
		}
		if(!accountServiceKey.equals(serviceKey)){
			return false;
		}
		
		//设置存在过期时间
		accountCacheService.setExpire(cacheAccountServiceKey, 60 * 10, TimeUnit.SECONDS);
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

}
